<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\Staff;
use App\Models\User;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\response;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Validator;

class StaffController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    private $company_id;
    private $user;
    public function __construct()
    {
        if (\Auth::guard('api')->check()) {
            $getUser = \Auth::guard('api')->user();
            $user = User::find($getUser->id);
            if (!$this->getDevice()) {
                //app
                $user->company_id = $user->appcompany_id;
            }
            $this->user = $user;
            $this->company_id = $user->company_id;
        }
    }
    //新增保存
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), Staff::$rules, Staff::$message);
        if ($validator->fails()) {
            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
        }
        $mobile = $request->input('mobile');
        $m = Staff::where(['company_id' => $this->company_id, 'mobile' => $mobile])->first();
        if (!empty($m)) {
            if ($m->status == 0) {
                return response()->json(['code' => 500, 'msg' => '新增失败,手机号不能重复！']);
            }
        } else {
            $m = new Staff();
        }
        $user_id = 0;
        /*$get_user = User::where(['status' => 0, 'mobile' => $mobile])->first();
        if (!empty($get_user)) {
            $user_id = $get_user->id;
        }*/
        $deptId = $request->input('deptId');
        $m->company_id = $this->company_id;
        $m->user_id = $user_id;
        $m->dept_id = $deptId;
        $m->name = $request->input('name');
        $m->mobile = $mobile;
        $m->status = 0;
        $m->type = $request->input('type');
        $m->email = $request->input('email');
        $m->position = $request->input('position');
        $m->employee_no = $request->input('employeeNo');
        $m->entry_time = $request->input('entryTime');
        $m->remarks = $request->input('remarks');
        $result = $m->save();
        if ($result) {
            return $this->respond('add_ok');
        }
        return $this->respond('add_error');
    }
    //获取单条记录
    public function get($id)
    {
        $data = Staff::find($id);
        if (!empty($data)) {
            return $this->respond('get_ok', $data);
        }
        return $this->respond('get_error');
    }
    //更新保存
    public function put(Request $request, $id)
    {
        if (empty($id)) {
            return response()->json(['code' => 500, 'msg' => '员工id不能为空']);
        }
        $company_id = $this->company_id;
        $validator = Validator::make($request->all(), Staff::$rules_edit, Staff::$message);
        if ($validator->fails()) {
            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
        }

        $model = new Staff();
        $m = $model::find($id);
        if (empty($m)) {
            return $this->respond('get_error');
        }
        $name = $request->input('name');
        $m->name = $name;
        $m->type = $request->input('type');
        $m->email = $request->input('email');
        $m->position = $request->input('position');
        $m->employee_no = $request->input('employeeNo');
        $m->entry_time = $request->input('entryTime');
        $m->remarks = $request->input('remarks');
        DB::beginTransaction();
        try {
            //中间逻辑代码
            $m->save();
            $getUser = User::where(['mobile' => $m->mobile, 'status' => 0])->first();
            if (!empty($getUser)) {
                $getUser->name = $name;
                $getUser->save();
            }
            DB::commit();
            return $this->respond('update_ok');
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return $this->respond('update_error');
        }
    }
    //删除员工
    public function remove(Request $request)
    {
        $id = $request->input('id');
        if (empty($id) || !is_array($id)) {
            return $this->respond('empty_error');
        }
        $check_status = Staff::whereIn('id', $id)->where('role_status', 1)->first();
        if (!empty($check_status)) {
            return response()->json(['code' => 500, 'msg' => '所选员工列表中包含超级管理员，不允许删除']);
        }
        $result = Staff::whereIn('id', $id)->update(['status' => 1]);
        if ($result) {
            return $this->respond('delete_ok');
        }
        return $this->respond('delete_error');
    }

    public function moveStaff(Request $request)
    {
        $node_ids = [];
        $id = $request->input('id');
        $deptId = $request->input('deptId');
        if (empty($deptId) || empty($deptId)) {
            return $this->respond('empty_error');
        }
        if (empty($id) || !is_array($id)) {
            return $this->respond('empty_error');
        }
        $model = Staff::whereIn('id', $id)->get();
        if (empty($model)) {
            return $this->respond('get_error');
        }
        $pnode = Department::where(['company_id' => $this->company_id, 'depth' => 1])->first();
        $childs = $pnode->getDescendantsAndSelf(['id as dept_id']);
        if (!empty($childs)) {
            $arr = $childs->toArray();
            $ids = array_column($arr, 'dept_id');
            if (in_array($deptId, $ids)) {
                $result = Staff::whereIn('id', $id)->update(['dept_id' => $deptId]);
                if ($result) {
                    return $this->respond('op_ok');
                }
                return $this->respond('op_error');
            }
            return response()->json(['code' => 500, 'msg' => '不能将员工移动到该部门下面']);
        }
    }
    public function export(Request $request)
    {
        $title = "员工信息表" . time();
        $deptId = $request->input('deptId');
        if (empty($deptId)) {
            return $this->respond('empty_error');
        }
        $node = Department::find($deptId);
        if (empty($node)) {
            return $this->respond('get_error');
        }
        $id_str = $node->getDescendantsAndSelf(['id as dept_id']);
        $data = DB::table('staff')->whereIn('dept_id', $id_str)->where('status', 0)->get();
        if (empty($data)) {
            return response()->json(['code' => 500, 'msg' => '数据为空不能导出']);
        }
        $cellData = [['姓名', '手机号', '邮箱', '职位', '工号', '入职日期', '备注', '创建时间']];
        foreach ($data as $key => $value) {
            $get_date = date('Y-m-d H:i:s', $value->created_at);
            $entry_time = "";
            if (!empty($value->entry_time)) {
                $entry_time = date('Y-m-d', $value->entry_time);
            }
            $cellData[$key + 1] = [
                $value->name, $value->mobile, $value->email, $value->position,
                $value->employee_no, $entry_time, $value->remarks, $get_date,
            ];
        }
        Excel::create($title, function ($excel) use ($cellData) {
            $excel->sheet('staff', function ($sheet) use ($cellData) {
                $sheet->rows($cellData);
            });
        })->store('xls', 'uploads/excel');
        $path['filepath'] = 'uploads/excel/' . $title . '.xls';
        return response()->json(['code' => 200, 'msg' => '导出数据成功', 'data' => $path]);
    }
    public function import(Request $request)
    {
        $deptId = $request->input('deptId');
        $file = $request->file('file');
        if (empty($file) || empty($deptId)) {
            return $this->respond('empty_error');
        }
        // 获取文件后缀名
        $exe = $file->getClientOriginalExtension();
        $exe = strtolower($exe);
        if (!in_array($exe, ['xls', 'xlsx'])) {
            return response()->json(array('code' => 500, 'msg' => '请上传后缀名为xls、xlsx的文件'));
        }
        $res = [];
        $data = [];
        Excel::load($file, function ($reader) use (&$res) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
        });
        $company_id = $this->company_id;
        if (empty($company_id)) {
            return response()->json(['code' => 500, 'msg' => '请先完善公司信息']);
        }
        $arr_index = 0;
        $check_staff = [];
        foreach ($res as $key => $value) {
            if ($key > 0) {
                if (empty($value[0]) && empty($value[1]) && empty($value[2]) && empty($value[3]) && empty($value[4]) && empty($value[5]) && empty($value[6])) {
                    break;
                }
                if (empty($value[0]) || empty($value[1])) {
                    return response()->json(['code' => 500, 'msg' => '姓名或电话不能为空']);
                }
                $data[$arr_index]['dept_id'] = $deptId;
                $data[$arr_index]['user_id'] = 0;
                $data[$arr_index]['company_id'] = $company_id;
                $data[$arr_index]['name'] = $value[0];
                $data[$arr_index]['mobile'] = $value[1];
                $data[$arr_index]['email'] = $value[2];
                $data[$arr_index]['position'] = $value[3];
                $data[$arr_index]['employee_no'] = $value[4];
                $data[$arr_index]['entry_time'] = strtotime($value[5]);
                $data[$arr_index]['remarks'] = $value[6];
                $data[$arr_index]['created_at'] = time();
                $data[$arr_index]['updated_at'] = time();
                $check_staff[$arr_index] = $value[1];
                $arr_index++;
            }
        }
        if (empty($data)) {
            return response()->json(['code' => 500, 'msg' => '数据源为空,不能导入']);
        }
        $unique_arr = array_unique($check_staff);
        if (!empty($check_staff) && count($unique_arr) != count($data)) {
            return response()->json(['code' => 500, 'msg' => '导入失败,手机号不能重复']);
        }
        $check_staff_data = Staff::where(['company_id' => $this->company_id, 'status' => 0])->whereIn('mobile', $unique_arr)->first();
        if (!empty($check_staff_data)) {
            return response()->json(['code' => 500, 'msg' => '导入失败,手机号不能重复']);
        }

        $check_staff_data_del = Staff::where(['company_id' => $this->company_id, 'status' => 1])->whereIn('mobile', $unique_arr)->pluck('mobile', 'id');
        //更新已有员工表数据
        $get_data = [];
        DB::beginTransaction();
        try {
            //中间逻辑代码
            if (!empty($check_staff_data_del)) {
                //
                $arr = $check_staff_data_del->toArray();
                $arr_keys = array_keys($arr);
                $arr_values = array_values($arr);
                foreach ($data as $k => $val) {
                    if (in_array($val['mobile'], $arr_values)) {
                        $get_key = array_search($val['mobile'], $arr_values);
                        $ids = $arr_keys[$get_key];
                        $val['status'] = 0;
                        unset($val['user_id']);
                        //更新员工表
                        Staff::where('id', $ids)->update($val);
                        //更新用户表
                        $getUser = User::where(['mobile' => $val['mobile'], 'status' => 0])->first();
                        if (!empty($getUser)) {
                            $getUser->name = $val['name'];
                            $getUser->save();
                        }
                        unset($data[$k]);
                    }
                }

            }
            foreach ($data as $key => $value) {
                DB::table('staff')->insert($value);
                //更新员工表
                $getUser = User::where(['mobile' => $value['mobile'], 'status' => 0])->first();
                if (!empty($getUser)) {
                    $getStaff = Staff::where(['status' => 0, 'company_id' => $company_id, 'mobile' => $value['mobile']])->first();
                    if (!empty($getStaff)) {
                        $getStaff->user_id = $getUser->id;
                        $getStaff->save();
                    }
                }
            }
            DB::commit();
            return response()->json(['code' => 200, 'msg' => '导入数据成功']);
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            dd($e);
            return response()->json(['code' => 500, 'msg' => '导入数据失败']);
        }
    }
}
